<template>
	<view class="userInfo">
		<u-form :model="form" label-width="150" label-align="center" ref="uForm">
			<u-form-item label="姓名" prop="userName">
				<u-input
					v-model="form.userName"
					clearable
					placeholder="请输入姓名"
					:disabled="isCheck"
				/>
			</u-form-item>
			<u-form-item label="身份证" prop="userIdcode">
				<u-input
					v-model="form.userIdcode"
					clearable
					type="idcard"
					placeholder="请输入身份证"
					:disabled="isCheck"
				/>
			</u-form-item>
		</u-form>
		<view class="submit" v-show="!isCheck">
			<u-button @click="submit" type="primary">提交</u-button>
		</view>
	</view>
</template>

<script>
import { userCompleteInfo } from '../../http/api'
export default {
	data() {
		return {
			form: {
				userName: '',
				userIdcode: '',
			},
			rules: {
				userName: [
					{
						required: true,
						message: '请输入姓名',
						trigger: 'blur,change',
					},
				],
				userIdcode: [
					{
						required: true,
						message: '请输入姓名',
						trigger: 'change',
					},
					{
						validator: (rule, value, callback) => {
							return this.$u.test.idCard(value)
						},
						message: '请检查身份证号',
						trigger: ['change', 'blur'],
					},
				],
			},
			isCheck: false,
		}
	},
	onLoad(option) {
		this.isCheck = option.isCheck === 'true'
		if (this.isCheck) {
			this.form = Object.assign({}, this.$store.state.userInfo)
		}
	},
	methods: {
		submit() {
			this.$refs.uForm.validate(valid => {
				if (valid) {
					// console.log(this.$store.state.userInfo)
					let sex = this.getSex(this.form.userIdcode)
					let obj = Object.assign({}, this.$store.state.userInfo, this.form)
					obj.userGender = sex
					userCompleteInfo(obj).then(({ head }) => {
						if (head.code == 200) {
							this.$store.commit('updateUser', obj)
							uni.reLaunch({
								url: '/pages/index/index',
							})
						}
					})
				} else {
					console.log('验证失败')
				}
			})
		},
		getSex(iden) {
			let sex = null
			let val = iden.length
			if (val === 18) {
				sex = iden.substring(16, 17)
			}
			if (val === 15) {
				sex = iden.substring(13, 14)
			}

			if (sex % 2 === 0) sex = 2
			else sex = 1
			return sex
		},
	},

	onReady() {
		this.$refs.uForm.setRules(this.rules)
	},
}
</script>
<style lang='scss'>
.userInfo {
	padding: 25rpx;
	box-sizing: border-box;

	.submit {
		margin-top: 50rpx;
	}
}
</style>